package org.reenscape.lib;
import java.sql.*;
import java.io.*;

/**
 * Contains all MySQL methods.
 */

public class MySQL {
	
	/**
	 * MySQL Connection
	 */
	public static Connection con;
	public static Statement stmt;
	
	/**
	 * Inital connection to a MySQL server.
	 * @param user Username of the MySQL account used to connect.
	 * @param pass Password of the MySQL account used to connect.
	 * @param URL The URL where the MySQL server is.
	 * @param port The port used to connect. -1 is default (3306).
	 * @param DB Database to connect to.
	 */
	public static void connect(String user, String pass, String URL, int port, String DB) {
	//System.out.println(user+","+pass+","+URL+","+port+","+DB);
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://" + URL + ":"+ port +"/"+ DB , user, pass);
			stmt = con.createStatement();
			Print.println("Connected to MySQL [" + con.toString() + "].");
		} catch( Exception e ) {
			Print.error("Connection rejected to MySQL database. Please check internet connection and login details.", "MySQL", "connect(String user, String pass, String URL, int port, String DB)", e);
		}
	}
	
	public static void disconnect() {
		Print.debug("Disconnected from MySQL [" + con.toString() + "].");
		con = null;
		stmt = null;
	}
	
	/**
	 * Send an update to a MySQL server. Returns NO ResultSet.
	 * @param query Query to send to server.
	 */
	public static void update(String query) {
		try {
			stmt.executeUpdate(query);
		} catch( Exception e ) {
			Print.error("Error in ResultSet rs.", "MySQL", "query(String query)", e);
		}
	}
	/**
	 * Send a query to the server, and return a ResultSet.
	 * @param query Query to execute.
	 * @return ResultSet of the query executed.
	 */
	public static ResultSet query(String query) {
		try {
			ResultSet rs = stmt.executeQuery(query);
			return rs;
		} catch( Exception e ) {
			Print.error("Error in ResultSet rs.", "MySQL", "query(String query)", e);
			return null;
		}
	}
	/**
	 * Counts the number of rows in a MySQL query.
	 * @param query Query to count rows from.
	 * @return Rows found.
	 */
	public static int count(String query) {
		try {
			ResultSet rs = stmt.executeQuery(query);
			if(rs.next()){
			return rs.getInt(1);
			} else {
			System.out.println("Unable to count rows!");
			throw new SQLException();
			}
		} catch( Exception e ) {
			Print.error("Error in ResultSet rs.", "MySQL", "count(String query)", e);
			return 0;
		}
	}
}